#-*- coding:utf-8 -*-

from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt
from django.utils import simplejson

from market.models import GType, Goods, Comment
from market.forms import AddGoodsForm, UploadImageForm
from market.manager import setGoodsImage


GOODS_NUM_OF_PAGE = 20


def index(request):
    return render(request, "market/index.html", {'gtypes':GType.objects.all()})


def latest_goods(request, page_num):
    _pagenum = int(page_num)
    goods_qs = Goods.objects.filter(status=Goods.STATUS_NORMAL)
    paginator = Paginator(goods_qs, GOODS_NUM_OF_PAGE)

    try:
        goods_list = paginator.page(page_num)
    except EmptyPage:
        goods_list = paginator.page(paginator.num_pages)

    return render(request, "market/goods_list.html", {'goods_list': goods_list, 'page':paginator})


def goods_list(request, type_id, page_num):
    _typeid = int(type_id)
    _pagenum = int(page_num)

    gtype = get_object_or_404(GType, pk=_typeid)
    goods_qs = Goods.objects.filter(status=Goods.STATUS_NORMAL, gtype_id = _typeid)
    paginator = Paginator(goods_qs, GOODS_NUM_OF_PAGE)

    try:
        goods_list = paginator.page(page_num)
    except EmptyPage:
        goods_list = paginator.page(paginator.num_pages)

    return render(request, "market/goods_list.html", {'goods_list': goods_list, 'page':paginator,'gtype':gtype})


def goods_detail(request, goods_id):
    _goodsid = int(goods_id)
    goods = get_object_or_404(Goods, pk=_goodsid)
    goods.reads = goods.reads + 1
    goods.save()
    return render(request, "market/goods_detail.html", {"goods": goods}) 


@login_required
def add_goods(request):
    if request.method == 'GET':
        f = AddGoodsForm()
        imgform = UploadImageForm()
        return render(request, "market/add_goods.html", {"form":f, "imgform":imgform})
        
    f = AddGoodsForm(request.POST)
    if f.is_valid():
        goods = f.save(False)
        goods.user = request.user
        goods.save()

        for imgname in request.POST.getlist('userimg', []):
            setGoodsImage(request.user, imgname, goods)

        return redirect("/market/goods/%d/"%(goods.id))

    else:
        imgform = UploadImageForm()
        return render(request, "market/add_goods.html", {"form":f, "imgform":imgform})


@login_required
@csrf_exempt
def comment(request, goods_id):
    _goodsid = goods_id
    if request.method != 'POST': 
        raise Http404()

    content = request.POST.get('content', '') 
    if len(content) == 0:
        raise Http404()

    goods = get_object_or_404(Goods, pk=_goodsid)
    json = {}
    c = Comment()
    c.goods = goods
    c.customer= request.user
    c.content = content
    c.save()
    json['ret'] = True
    json['author'] = request.user.username
    json['content'] = content
    json['posttime'] = c.posttime.strftime("%Y-%m-%d %H:%M:%S") 
    goods.comments = goods.comments + 1
    goods.save()

    return HttpResponse(simplejson.dumps(json))


@login_required
def upload_image(request):
    if request.method == 'GET':
        f = UploadImageForm()
        return render(request, "market/upload.html", {"form":f})
    else:
        f = UploadImageForm(request.POST, request.FILES)
        if f.is_valid():
            img = f.save(False)
            img.owner= request.user
            img.size = img.image.size
            img.save()
            img.relative_path = img.image.name
            img.save()

            imgurl = "/static/%s/" % (img.image.name)
            return render(request, "market/upload_iframe.html", {"imgurl":imgurl, "imgname":img.image.name})

        return HttpResponse("What ???")

